<?php
namespace Admin\Controller;
use Common\Controller\AdminbaseController;
class BbsController extends AdminbaseController {

    protected $bbs_model,$bbsComment_model,$bbsLike_model,$bbsType_model,$bbsComplain_model;


    public function _initialize() {
        parent::_initialize();
        $this->bbs_model = D("Bbs");
        $this->bbsComment_model = D("BbsComment");
        $this->bbsLike_model = M("BbsLike");
        $this->bbsType_model = M("BbsType");
        $this->bbsComplain_model = M("BbsComplain");
    }

    public function index1()
    {
        $id=I('type_id/d',0);
        $this->_index($id);
    }

    public function index2()
    {
        $id=I('type_id/d',0);
        $this->_index($id);
    }

    public function index3()
    {
        $id=I('type_id/d',0);
        $this->_index($id);
    }

    public function index4()
    {
        $id=I('type_id/d',0);
        $this->_index($id);
    }

    public function index5()
    {
        $id=I('type_id/d',0);
        $this->_index($id);
    }

    /**
     * 社区帖子列表
     */
    private function _index($id){
        $where = array("b.type_id"=>$id);

        $type=$this->_getBBSType($id);

        /**是否加精**/
        $istop=I('request.istop');
        if(is_numeric($istop) && $istop!==""){
            $where['b.istop']=array(
                array('EQ',$istop)
            );
        }

        $start_time=I('request.start_time');
        if(!empty($start_time)){
            $start_time=strtotime($start_time);
            $where['b.create_time']=array(
                array('EGT',$start_time)
            );
        }

        $end_time=I('request.end_time');
        if(!empty($end_time)){
            $end_time=strtotime($end_time);
            if(empty($where['b.create_time'])){
                $where['b.create_time']=array();
            }
            array_push($where['b.create_time'], array('ELT',$end_time));
        }

        $keyword=I('request.keyword');
        if(!empty($keyword)){
            $keywordSearch['b.title'] = array('like',"%$keyword%");
            $keywordSearch['b.content'] = array('like',"%$keyword%");
            $keywordSearch['_logic'] = 'or';
            $where['_complex'] = $keywordSearch;
        }
        //dump($where);exit;

        $count=$this->bbs_model->alias("b")->where($where)->count();
        $page = $this->page($count, 20);

        $bbs=$this->bbs_model
            ->alias("b")
            ->join("__BBS_LIKE__ l ON b.id=l.bbs_id",'LEFT')
            ->where($where)
            ->field("b.id,b.title,LEFT(b.content,200) AS content,b.hits,b.istop,b.isstar,b.create_time,count(l.id) as likes,b.status,b.listorder")
            ->group("b.id")
            ->order("b.isstar DESC,b.istop DESC,b.listorder DESC,b.id DESC")
            ->limit($page->firstRow, $page->listRows)
            //->fetchSql(true)
            ->select();
        //dump($bbs);exit;
        //
        foreach ($bbs as &$value) {
            //$value['content']=htmlspecialchars($value['content']);
            $value['content']=strip_tags($value['content']);
            $value['content']=substr_for_utf8($value['content'],60);
        }


        $this->assign("formget",I("request."));
        $this->assign("page", $page->show('Admin'));
        $this->assign('bbs',$bbs);
        $this->assign('type',$type);
        $this->display("index");
    }

    public function pageShow(){
        $id=I('get.id',0,'intval');
        $where=array();
        $where['b.id'] = array('eq',$id);
        //$where['status'] = array('eq',1);

        $content = $this->bbs_model
                    ->alias("b")
                    ->join("__FILE__ as i ON FIND_IN_SET(i.id,b.image_ids) >0",'LEFT')/*帖子图片*/
                    ->where($where)
                    ->field("b.*,GROUP_CONCAT( DISTINCT CONCAT_WS(',',i.id,i.path) SEPARATOR '|') AS images")
                    ->group("b.id")
                    ->find();
        //dump($content);exit;

        if(empty($content)){
            header('HTTP/1.1 404 Not Found');
            header('Status:404 Not Found');
            if(sp_template_file_exists(MODULE_NAME."/404")){
                $this->display(":404");
            }
            return ;
        }

        $this->assign($content);
        $this->display(":h5");
    }

    /**
     * 社区评论
     */
    public function commentIndex(){
        $where = array();
        /**搜索条件**/

        /**
         * 如果指定帖子ID则只显示该帖子的评论
         */
        $bbsId=I('request.bbs_id');
        if(!empty($bbsId)){
            $where['bbs_id'] = $bbsId;
        }

        $start_time=I('request.start_time');
        if(!empty($start_time)){
            $start_time=strtotime($start_time);
            $where['create_time']=array(
                array('EGT',$start_time)
            );
        }

        $end_time=I('request.end_time');
        if(!empty($end_time)){
            $end_time=strtotime($end_time);
            if(empty($where['create_time'])){
                $where['create_time']=array();
            }
            array_push($where['create_time'], array('ELT',$end_time));
        }

        $keyword=I('request.keyword');
        if(!empty($keyword)){
            $where['content'] = array('like',"%$keyword%");
        }
        //dump($where);

        $count=$this->bbsComment_model->where($where)->count();
        $page = $this->page($count, 20);

        $comments=$this->bbsComment_model
            ->where($where)
            ->order("id DESC")
            ->limit($page->firstRow, $page->listRows)
            //->fetchSql(true)
            ->select();
        //dump($bbs);//exit;
        $this->assign("formget",I("request."));
        $this->assign("page", $page->show('Admin'));
        $this->assign('comments',$comments);
        $this->display("Bbs/Comment/index");
    }

    public function add(){
        $id=I("id",0);
        $type_id=I('type_id/d',0);
        $type=$this->_getBBSType($type_id);
        //dump($type);

        $info=[];
        if (!empty($id)){
            $where=["id"=>$id];
            $info=$this->bbs_model
                    ->where($where)
                    ->find();
            //dump($info);exit;
        }

        $this->assign("info", $info);
        $this->assign("type", $type);
        $this->display();
    }

    public function addDo(){
        if (IS_POST) {
            $_POST['post']['user_type']=3;
            $_POST['post']['user_id']=sp_get_current_admin_id();
            $data=I("post.post");
            //dump($data);exit;
            $data['content']=htmlspecialchars_decode($data['content']);
            $host=get_host_name();
            $data['content']=str_replace('<img src="/', '<img src="'.$host.'/', $data['content']);
            $create=$this->bbs_model->create($data);
            if (isset($data['id']) && $data['id']>0) {
                $result=$this->bbs_model->save();
            }else{
                $result=$this->bbs_model->add();
            }

            
            if ($create!==false && $result!==false) {
                $this->success("成功！",U("index".$data['type_id'],["type_id"=>$data['type_id']]));
            } else {
                $this->error("失败！");
            }
        }
    }

    /**
     * 投诉
     */
    public function complain(){
        $where = array();
        /**搜索条件**/

        $type=I('request.type_id');
        if(!empty($type)){
            $where['bbs_id'] = $type;
        }

        $join=$this->_getComplainJoin();
        $field=$this->_getComplainField();
        //dump($where);

        $count==$this->bbsComplain_model
                    ->alias("c")
                    ->join($join)
                    ->where($where)
                    ->group("c.id")
                    ->count();

        $page = $this->page($count, 20);

        $data=$this->bbsComplain_model
                    ->alias("c")
                    ->join($join)
                    ->where($where)
                    ->field($field)
                    ->group("c.id")
                    ->order("c.id DESC")
                    ->limit($page->firstRow, $page->listRows)
                    //->fetchSql(true)
                    ->select();
        

        foreach ($data as &$value){
            $value['images']=analysisImages($value['images']);
        }
        unset($value);

        //dump($data);//exit;
        
        $types=$this->_getBBSTypeAll();

        $this->assign("formget",I("request."));
        $this->assign("page", $page->show('Admin'));
        $this->assign('data',$data);
        $this->assign('types',$types);
        $this->display();
    }

    public function complainDetail(){
        $id=I('get.id',0,'intval');
        $where = array();
        /**搜索条件**/


        $where['c.id'] = array('eq',$id);

        $join=$this->_getComplainJoin();
        $field=$this->_getComplainField();
        //dump($where);

        $data=$this->bbsComplain_model
                    ->alias("c")
                    ->join($join)
                    ->where($where)
                    ->field($field)
                    ->group("c.id")
                    //->fetchSql(true)
                    ->find();
        

        $data['images']=analysisImages($data['images']);
        //dump($data);exit;

        if(empty($data)){
            header('HTTP/1.1 404 Not Found');
            header('Status:404 Not Found');
            if(sp_template_file_exists(MODULE_NAME."/404")){
                $this->display(":404");
            }
            return ;
        }

        $this->assign($data);
        $this->display();
    }

    public function complainStatus(){
        $ids = I('ids');
        $status=I('request.status');
        if (empty($ids) || !is_numeric($status)){
            $this->error("参数错误!");
        }
        $statusInfo=$this->_statusinfo();
        if (parent::_setStatus($this->bbsComplain_model,$ids,$status)!==false) {
            $this->success("成功");
        } else {
            $this->error("失败");
        }
    }

    /**
     * 评论显示/隐藏
     */
    public function commentStatus(){
        $ids = I('ids');
        $status=I('request.status');
        if (empty($ids) || !is_numeric($status)){
            $this->error("参数错误!");
        }
        $statusInfo=$this->_statusinfo();
        if (parent::_setStatus($this->bbsComment_model,$ids,$status)!==false) {
            $this->success($statusInfo[$status]['success']);
        } else {
            $this->error($statusInfo[$status]['error']);
        }
    }

    /**
     * 评论删除
     */
    public function commentDelete(){
        $ids = I("ids");
        $status = parent::_delete($this->bbsComment_model,$ids);

        if ($status) {
            $this->success("删除成功！");
        } else {
            $this->error("删除失败！");
        }
    }

    public function commentShow(){
        $id=I('get.id',0,'intval');
        $where=array();
        $where['id'] = array('eq',$id);
        //$where['status'] = array('eq',1);

        $content = $this->bbsComment_model->where($where)->find();

        if(empty($content)){
            header('HTTP/1.1 404 Not Found');
            header('Status:404 Not Found');
            if(sp_template_file_exists(MODULE_NAME."/404")){
                $this->display(":404");
            }
            return ;
        }

        $this->assign($content);
        $this->display("h5");
    }


    /**
     * 社区帖子排序
     */
    public function listorders() {
        $status = parent::_listorders($this->bbs_model);
        if ($status) {
            $this->success("排序更新成功！");
        } else {
            $this->error("排序更新失败！");
        }
    }

    // 帖子删除
    public function delete(){
        $ids = I("ids");
        $status = parent::_delete($this->bbs_model,$ids);

        if ($status) {
            $this->success("删除成功！");
        } else {
            $this->error("删除失败！");
        }
    }

    // 帖子置顶
    public function top(){
        $ids = I('ids');
        $istop = I('request.istop');
        if (empty($ids) || !is_numeric($istop)){
            $this->error("参数错误!");
        }
        $info=[
            0=>[
                "success"=>"取消置顶成功",
                "error"=>"取消置顶失败"
            ],
            1=>[
                "success"=>"置顶成功",
                "error"=>"置顶失败"
            ],
        ];
        if (is_array($ids)){
            $where=array("id"=>array('in',$ids));
        }else{
            $where=array("id"=>$ids);
        }

        if ( $this->bbs_model->where($where)->save(array('istop'=>$istop))!==false) {
            $data=$this->bbs_model->where($where)->field("DISTINCT(user_id)")->select();
            //dump($data);exit;
            $this->success($info[$istop]['success']);
        } else {
            $this->error($info[$istop]['error']);
        }
    }

    // 帖子加精
    public function star(){
        $ids = I('ids');
        $status = I('request.isstar');
        if (empty($ids) || !is_numeric($status)){
            $this->error("参数错误!");
        }
        $info=[
            0=>[
                "success"=>"取消加精成功",
                "error"=>"取消加精失败"
            ],
            1=>[
                "success"=>"加精成功",
                "error"=>"加精失败"
            ],
        ];
        if (is_array($ids)){
            $where=array("id"=>array('in',$ids));
        }else{
            $where=array("id"=>$ids);
        }

        if ( $this->bbs_model->where($where)->save(array('isstar'=>$status))!==false) {
            $data=$this->bbs_model->where($where)->field("DISTINCT(user_id)")->select();
            //dump($data);exit;
            $this->success($info[$status]['success']);
        } else {
            $this->error($info[$status]['error']);
        }
    }

    public function status(){
        $ids = I('ids');
        $status=I('request.status');
        if (empty($ids) || !is_numeric($status)){
            $this->error("参数错误!");
        }
        $statusInfo=$this->_statusinfo();
        if (parent::_setStatus($this->bbs_model,$ids,$status)!==false) {
            $this->success($statusInfo[$status]['success']);
        } else {
            $this->error($statusInfo[$status]['error']);
        }
    }

    private function _getBBSType($id)
    {
        return $this->bbsType_model->where(["id"=>$id])->cache(86400)->field("id,name")->find();
    }

    private function _getBBSTypeAll()
    {
        return $this->bbsType_model->cache(86400)->field("id,name")->select();
    }

    private function _getComplainJoin()
    {
        return [
            "JOIN __BBS__ b ON c.bbs_id=b.id",
            "LEFT JOIN __FILE__ as i ON FIND_IN_SET(i.id,c.image_ids) >0",/*投诉图片*/
            "LEFT JOIN __USER__ as u ON c.user_id=u.id AND c.user_type=1",
            "LEFT JOIN __BUSINESS__ as s ON c.user_id=s.id AND c.user_type=2"
        ];
    }

    private function _getComplainField()
    {
        return "
            c.*,GROUP_CONCAT( DISTINCT CONCAT_WS(',',i.id,i.path) SEPARATOR '|') AS images,
            IF(c.user_type>1,s.name,u.username) as username,
            IF(c.user_type>1,s.phone,u.phone) as phone,
            b.title as bbs_title
            ";
    }
}